package com.test.designpattern.chainOfResponsibility.demo2;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class OptHandlerChain {

    @Autowired
    private List<IOptHandler> handlers;
    // 开始执行的责任链下标
    private Integer index = 0;

    // 排序
    public OptHandlerChain(List<IOptHandler> handlers) {
        this.handlers = handlers.stream().sorted(Comparator.comparing(IOptHandler::getOrder)).collect(Collectors.toList());
    }

    public void process(Object obj) {
//        if (index == 0) {
//            System.out.println("责任链执行开始...");
//        }
//
//        if (index == handlers.size()) {
//            System.out.println("责任链执行结束...");
//        }

        if (index < handlers.size()) {
            IOptHandler handler = handlers.get(index++);
            handler.handle(obj, this);
        }
    }
}
